import 'dart:async';

import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/Xwidgets/button_widget.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/Xwidgets/line.dart';
import 'package:yp/Xwidgets/pay_bottom_sheet.dart';
import 'package:yp/Xwidgets/shop.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/rules.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/services/api.dart';
import 'package:yp/widgets/dialog.dart';

import '../../../helper.dart';
import '../../../router.dart';
import 'order_logic.dart';
import 'order_state.dart';

final List orderStateList = ['待付款', '待发货', '拼团中', '已发货', '待自提', '待评价', '已完成'];

class OrderPage extends StatefulWidget {
  @override
  _OrderPageState createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> with TickerProviderStateMixin {
  TabController _controller;

  var _tabList = [
    Tab(text: '全部'),
    Tab(text: '待付款'),
    Tab(text: '待配送/自提'),
    Tab(text: '待送达'),
    Tab(text: '待评价'),
    Tab(text: '售后'),
  ];
  int index;

  @override
  void initState() {
    super.initState();
    _controller =
        TabController(initialIndex: 0, length: _tabList.length, vsync: this);
    Get.put(OrderLogic());
    Get.find<OrderLogic>()
        .getOrderInfoList(list: List.generate(_tabList.length, (index) => []));
    Get.find<OrderLogic>().state.refreshControllerList = List.generate(
        _tabList.length, (index) => RefreshController(initialRefresh: true));
    index = Get.arguments['index'] != null ? Get.arguments['index'] : 0;
    _controller = TabController(
        initialIndex: index, length: _tabList.length, vsync: this);
  }

  @override
  void dispose() async {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Get.put(OrderLogic());
    // final state = Get.find<OrderLogic>().state;
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Config.mainColor,
          brightness: Brightness.light,
          iconTheme: IconThemeData(color: Colors.white),
          title: Text(
            "订单列表",
            style: TextStyle(color: Colors.white, fontSize: 32.sp),
          ),
          centerTitle: true,
          elevation: 0,
        ),
        body: Container(
          color: const Color(0xffffffff),
          child: GetBuilder<OrderLogic>(builder: (logic) {
            return Column(
              children: [
                Container(
                  height: 30,
                  margin: EdgeInsets.symmetric(horizontal: 15, vertical: 10),
                  decoration: BoxDecoration(
                      color: const Color(0xfff3f4f6),
                      borderRadius: BorderRadius.circular(20)),
                  child: TextField(
                    controller: logic.state.searchTextEditingController,
                    maxLines: 1,
                    style: TextStyle(
                      color: Color(0xff222222),
                      fontSize: 14,
                    ),
                    decoration: InputDecoration(
                      fillColor: const Color(0xfff3f4f6),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.all(0),
                      hintText: '请输入关键字',
                      hintStyle: TextStyle(
                        color: Color(0xff808080),
                        fontSize: 14,
                      ),
                      enabledBorder: OutlineInputBorder(
                        // 设置输入框可编辑时的边框样式
                        borderRadius:
                            BorderRadius.all(Radius.circular(90)), // 设置边框四个角的弧度
                        // borderSide: BorderSide(
                        //   // 用来配置边框的样式
                        //   color: Color(0xffEA5504),
                        //   width: setWidth(2), // 设置边框的粗细
                        // ),
                        borderSide: BorderSide.none,
                      ),
                      focusedBorder: OutlineInputBorder(
                        // 用来配置输入框获取焦点时的颜色
                        borderRadius:
                            BorderRadius.all(Radius.circular(90)), // 设置边框四个角的弧度
                        borderSide: BorderSide(
                          // 用来配置边框的样式
                          color: Colors.transparent, //设置边框的颜色
                          width: setWidth(2), // 设置边框的粗细
                        ),
                      ),
                      prefixIcon: InkWell(
                        onTap: () {
                          logic.searchOrderList(
                            index: _controller.index,
                            getOrderState: _getOrderState(_controller.index),
                          );
                        },
                        child: Container(
                          width: 15,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(setWidth(28)),
                              bottomLeft: Radius.circular(setWidth(28)),
                            ),
                          ),
                          alignment: Alignment.center,
                          child: Icon(
                            Icons.search,
                            color: const Color(0xff808080),
                            size: 20,
                          ),
                        ),
                      ),
                    ),
                    onSubmitted: (String text) {
                      logic.searchOrderList(
                        index: _controller.index,
                        getOrderState: _getOrderState(_controller.index),
                      );
                    },
                  ),
                ),
                _tabHeadder(),
                YpLine(
                  height: 20,
                  thickness: 20,
                  color: EsColors.BackGroundSecondary,
                ),
                _orderList(),
              ],
            );
          }),
        ));
  }

  /// 获取不同状态下的订单状态数组
  int _getOrderState(int type) {
    switch (type) {
      case 0:
        return 0;
        break;
      case 1:
        return 1;
        break;
      case 2:
        return 2;
        break;
      case 3:
        return 3;
        break;
      case 4:
        return 4;
        break;
      default:
        return 17;
        break;
    }
  }

  ///  tab栏切换的头部
  Widget _tabHeadder() {
    return Container(
      color: EsColors.White,
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: ExtendedTabBar(
        tabs: List<Widget>.generate(
            _controller.length, (int index) => _tabList[index]),
        controller: _controller,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.Primary,
        isScrollable: false,
        unselectedLabelColor: EsColors.TitleSecondary,
        indicatorSize: TabBarIndicatorSize.label,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        indicator: const ExtendedUnderlineTabIndicator(
          // size: 30,
          borderSide: BorderSide(color: EsColors.Primary, width: 2),
        ),
        onTap: (index) {
          setState(() {
            Get.find<OrderLogic>().searchOrderList(
              index: index,
              getOrderState: _getOrderState(index),
            );
          });
        },
      ),
    );
  }

  /// 下边对应的列表
  Widget _orderList() {
    return Expanded(
      child: TabBarView(
        controller: _controller,
        children: List<Widget>.generate(
            _controller.length,
            (int index) => OrderList(
                  orderState: _getOrderState(index),
                  tabIndex: index,
                )).toList(),
      ),
    );
  }
}

class OrderList extends StatefulWidget {
  /// 能够获取的数组  item状态随机
  final int orderState;
  final int tabIndex;

  const OrderList({
    Key key,
    this.orderState,
    this.tabIndex,
  }) : super(key: key);

  @override
  _OrderListState createState() => _OrderListState();
}

class _OrderListState extends State<OrderList>
    with AutomaticKeepAliveClientMixin {
  List _orderInfoList = [];
  int page = 1;

  OrderState state = Get.find<OrderLogic>().state;
  // RefreshController _refreshController =
  //     RefreshController(initialRefresh: true);
  RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController =
        Get.find<OrderLogic>().state.refreshControllerList[widget.tabIndex];
  }

  getOrderList() {
    var params = {
      "client_type": 1,
      "page": state.page,
      "page_size": 10,
      "order_status": widget.orderState,
      "access_token": SpUtil.getString('token'),
      "key_word":
          Get.find<OrderLogic>().state.searchTextEditingController.text.trim(),
      "channel_num_id": 99,
      "use_platform": 2,
    };
    Api.searchOrderList(params).listen((event) {
      if (mounted) {
        setState(() {
          // if (event['orders'] != null && event['orders'].length > 0) {
          if (event['order_list_page'] != null &&
              event['order_list_page']['content'] != null &&
              event['order_list_page']['content'].length > 0) {
            state.OrderInfoList[widget.tabIndex]
                .addAll(event['order_list_page']['content']);
            // _orderInfoList.addAll(event['order_list_page']['content']);
            // page++;
            state.page++;
            _refreshController.refreshCompleted();
            _refreshController.loadComplete();
          } else {
            _refreshController.refreshCompleted();
            _refreshController.loadNoData();
          }
          // Get.find<OrderLogic>()
          //     .getOrderInfoList(list: _orderInfoList, index: widget.tabIndex);
          // Get.lazyPut(() => OrderLogic());
          Get.find<OrderLogic>().getOrderInfoList(
              list: state.OrderInfoList[widget.tabIndex],
              index: widget.tabIndex);
        });
      }
    });
  }

  void _onRefresh() async {
    setState(() {
      Get.find<OrderLogic>().getOrderInfoList(list: [], index: widget.tabIndex);
      state.page = 1;
    });
    getOrderList();
  }

  void _onLoading() async {
    getOrderList();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      body: GetBuilder<OrderLogic>(
        builder: (logic) {
          List orderList =
              Get.find<OrderLogic>().state.OrderInfoList[widget.tabIndex];
          return SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: ClassicHeader(),
            footer: ClassicFooter(),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: orderList.length > 0
                ? ListView.separated(
                    itemBuilder: (context, index) {
                      return _orderItem(orderList, index, logic);
                    },
                    separatorBuilder: (context, index) => YpLine(
                        height: 20,
                        thickness: 20,
                        color: EsColors.BackGroundSecondary),
                    itemCount: orderList.length)
                : Center(
                    child: Text(
                      '暂无数据',
                      style: TextStyle(
                        color: Color(0xff999999),
                        fontSize: 28.w,
                      ),
                    ),
                  ),
          );
        },
      ),
    );
  }

  /// 订单item
  Widget _orderItem(List info, int index, OrderLogic logic) {
    return GestureDetector(
      onTap: () {
        /// 查看商品详情
        // print(info[index]['order_num_id']);
        // print(info[index]['order_status']);
        // return;
        if (widget.orderState == 17) {
          Get.toNamed(RouteConfig.applyDetail, arguments: {
            // 'id': info[index]['tml_num_id'],
            'id': info[index]['order_num_id'],
            "ordertype": 1,
            'status': 5,
          }).then((value) {
            _onRefresh();
            print('========123afdfafafasfd========>');
          });
        } else {
          Get.toNamed(RouteConfig.orderDetial, arguments: {
            // 'id': info[index]['tml_num_id'],
            'id': info[index]['order_num_id'],
            'status:': info[index]['order_status'],
          }).then((value) {
            _onRefresh();
            print('========123afdfafafasfd========>');
          });
        }
      },
      child: Container(
        color: EsColors.White,
        padding: const EdgeInsets.only(bottom: 14),
        child: Column(
          children: [
            ShopName(
              info[index]['ec_shop_name'],
              // shopState: info['shopState'],
              orderState: info[index]['order_status_name'],
            ),
            YpLine(),
            Container(
              padding: EdgeInsets.symmetric(
                horizontal: 30.w,
                vertical: 15.w,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "订单号：${info[index]['order_num_id']}",
                    style: TextStyle(
                      color: Color(0xff666666),
                      fontSize: 24.sp,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      Clipboard.setData(ClipboardData(
                          text: '${info[index]['order_num_id']}'));
                      toast("复制成功");
                    },
                    child: Text(
                      "复制",
                      style: TextStyle(
                        color: Color(0xff666666),
                        fontSize: 24.sp,
                      ),
                    ),
                  )
                ],
              ),
            ),
            GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (widget.orderState == 17) {
                    Get.toNamed(RouteConfig.applyDetail, arguments: {
                      // 'id': info[index]['tml_num_id'],
                      'id': info[index]['order_num_id'],
                      "ordertype": 1,
                      'status': 5,
                    }).then((value) {
                      print('========123afdfafafasfd========>');
                    });
                  } else {
                    Get.toNamed(RouteConfig.orderDetial, arguments: {
                      // 'id': info[index]['tml_num_id'],
                      'id': info[index]['order_num_id'],
                      'status:': info[index]['order_status'],
                      'info:': info[index],
                    });
                  }
                  print('查看购买商品');
                },
                child: info[index]['item_details'].length > 1
                    ? duoproduct(info, index)
                    : danproduct(info, index)),
            info[index]['so_sign'] == 19
                ? Container(
                    margin: EdgeInsets.only(left: 15, bottom: 15),
                    child: Row(
                      children: [
                        Text(
                          '预付差额时间:',
                          style: TextStyle(
                              color: const Color(0xff999999), fontSize: 12),
                        ),
                        Text(
                          " ${info[index]['balance_payment_dtme']}",
                          style: TextStyle(
                              color: const Color(0xffEA5504), fontSize: 12),
                        ),
                      ],
                    ),
                  )
                : SizedBox(),
            info[index]['so_sign'] == 40
                ? Container(
                    margin: EdgeInsets.only(left: 15),
                    child: Column(
                      children: [
                        Row(
                          children: [
                            Text(
                              '付尾款日期:',
                              style: TextStyle(
                                  color: const Color(0xff999999), fontSize: 12),
                            ),
                            Text(
                              " ${info[index]['balance_start_dtme']}",
                              style: TextStyle(
                                  color: const Color(0xffEA5504), fontSize: 12),
                            ),
                          ],
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 5, bottom: 15),
                          child: Row(
                            children: [
                              Text(
                                '发货日期:',
                                style: TextStyle(
                                    color: const Color(0xff999999),
                                    fontSize: 12),
                              ),
                              Expanded(
                                child: Text(
                                  " ${info[index]['deliver_dtme']}",
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 1,
                                  style: TextStyle(
                                      color: const Color(0xff333333),
                                      fontSize: 12),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  )
                : SizedBox(),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 30.w),
              margin: EdgeInsets.only(bottom: 30.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '共' + (info[index]['item_details'].length).toString() + '件',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: EsColors.ContentSecondary,
                        fontSize: EsSizes.SM,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  RichText(
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    text: TextSpan(
                        text: '${rules('a1', info[index]) ? '应付' : '实付'}：￥',
                        style: TextStyle(
                            fontSize: EsSizes.XS,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Normal),
                        children: <TextSpan>[
                          TextSpan(
                              text: rules('a1', info[index])
                                  ? info[index]['need_pay_amount'].toString()
                                  : info[index]['real_pay_amount'].toString(),
                              style: TextStyle(
                                  fontSize: EsSizes.XS,
                                  color: EsColors.TitleSecondary,
                                  fontWeight: EsFontWeights.Medium)),
                        ]),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                SizedBox(width: 12),

                Expanded(child: SizedBox()),
                ////按钮
                Padding(
                  padding: const EdgeInsets.only(right: 12),
                  child: _orderProgress(info[index], logic),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget danproduct(info, index) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Wrap(
            spacing: 6,
            children: List.generate(
              info[index]['item_details'].length > 5
                  ? 5
                  : info[index]['item_details'].length,
              (indexs) => CachedImage(
                width: (MediaQuery.of(context).size.width / 7),
                height: MediaQuery.of(context).size.width / 7,
                path: info[index]['item_details'][indexs]['item_picture'],
                border:
                    Border.all(color: EsColors.BackGroundSecondary, width: 1),
              ),
            ),
          ),
          SizedBox(
            width: 20.w,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Container(
                width: 500.w,
                height: 50.w,
                child: Text(
                  info[index]['item_details'][0]['item_name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Container(
                width: 500.w,
                child: Text(
                  (info[index]['item_details'][0]['spec_nature_info'] == null
                          ? ""
                          : "${info[index]['item_details'][0]['spec_nature_info']}") +
                      ("${info[index]['item_details'][0]['point_sale_type'] == 1 ? ' X${info[index]['item_details'][0]['qty'].abs().toStringAsFixed(2)}' : 'X${info[index]['item_details'][0]['qty'].abs().toInt()}'}"),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          )

          // SizedBox(width: 8),
          // Text(
          //   '共' +
          //       (info[index]['item_details'].length).toString() +
          //       '件',
          //   maxLines: 1,
          //   overflow: TextOverflow.ellipsis,
          //   style: TextStyle(
          //       color: EsColors.ContentSecondary,
          //       fontSize: EsSizes.SM,
          //       fontWeight: EsFontWeights.Normal),
          // )
        ],
      ),
    );
  }

  Widget duoproduct(info, index) {
    return Container(
      margin: const EdgeInsets.only(
        top: 12,
        left: 12,
        right: 12,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: List.generate(
          info[index]['item_details'].length > 5
              ? 5
              : info[index]['item_details'].length,
          (indexs) => Container(
            padding: EdgeInsets.only(bottom: 10.w),
            margin: EdgeInsets.only(bottom: 30.w),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Color(0xffE6E8E8),
                ),
              ),
            ),
            child: Row(
              children: [
                CachedImage(
                  width: 100.w,
                  height: 100.w,
                  path: info[index]['item_details'][indexs]['item_picture'],
                  border: Border.all(
                    color: EsColors.BackGroundSecondary,
                    width: 1,
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 120.w,
                    margin: EdgeInsets.only(left: 20.w),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            if (info[index]['item_details'][indexs]
                                    ['pmt_sign'] ==
                                1)
                              Container(
                                margin: EdgeInsets.only(top: 6, right: 6),
                                padding: EdgeInsets.fromLTRB(8, 3, 8, 3),
                                decoration: new BoxDecoration(
                                    border: new Border.all(
                                        color: Color(0xFFFF0000), width: 0.5),
                                    color: Colors.red,
                                    borderRadius:
                                        new BorderRadius.circular((9.0))),
                                alignment: Alignment.center,
                                child: Text(
                                  '赠品',
                                  style: TextStyle(
                                    fontSize: 18.sp,
                                    color: Color(0xffffffff),
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            Text(
                              info[index]['item_details'][indexs]['item_name'],
                              style: TextStyle(
                                fontSize: 24.sp,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        ),
                        Row(
                          children: [
                            Text(
                              // "¥${info[index]['item_details'][indexs]['total_trade_amount']}",
                              "¥${info[index]['item_details'][indexs]['trade_price']}",
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: Config.mainColor,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            Text(
                              " x${info[index]['item_details'][indexs]['point_sale_type'] == 1 ? info[index]['item_details'][indexs]['qty'].toDouble().toStringAsFixed(2) : info[index]['item_details'][indexs]['qty'].toInt()}",
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: Colors.black,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

  }

  /// 订单进度 不同状态下的右下角按钮
  Widget _orderProgress(info, OrderLogic logic) {
    return Row(
      children: [
        Visibility(
          visible: rules('a4', info),
          child: Row(children: [
            TimeButton(info, context),
            SizedBox(width: 12.w),
          ]),
        ), //去付款
        // EsOutLineButton(
        //   '订单详情',
        //   normal: true,
        //   onTap: () {
        //     print('订单详情');
        //   },
        // ),
        // SizedBox(width: 12.w),

        Visibility(
          // visible: rules('a7', info),
          visible: false,
          child: Row(children: [
            EsOutLineButton(
              '拼团详情',
              onTap: () {
                print('拼团详情');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ),

        Visibility(
          visible: rules('a2', info) && info['is_service_order'] != 1,
          child: Row(children: [
            EsOutLineButton(
              '查看物流',
              normal: true,
              onTap: () {
                Get.toNamed(RouteConfig.logistics, parameters: {
                  // 'tmlId': info["tml_num_id"],
                  'tmlId': info['order_num_id'],
                  'transCode': info["ship_tran_no_by_tml_num_ids"]
                });
                print('查看物流');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //

        if (info["order_status"] == 1 && info['unpay_button_type'] == 1)
          Row(children: [
            EsOutLineButton(
              '取消订单 ',
              normal: true,
              onTap: () {
                YpShowDialog.normalConfirm(context, '确定取消订单？',
                    normalOrder: false, leftCallback: () {
                  var params = {
                    'tml_num_id': info['order_num_id'],
                    'usr_num_id': SpUtil.getInt('empeNumId'),
                  };
                  Api.closeOrder(params).listen((event) {
                    if (event['code'] == 0) {
                      toast("操作成功");
                      logic.onReady();
                      info['order_status'] = 9;
                      info['order_status_name'] = '已取消';
                    } else {
                      toast(event["message"]);
                    }
                  });
                  print('下一步');
                });
              },
            ),
            SizedBox(width: 12.w),
          ]), //

        if (widget.orderState != 17 &&
            ((info["install_service_sign"] == 1 &&
                    info["order_status"] != 16) ||
                info['is_service_order'] == 1))
          Row(children: [
            EsOutLineButton(
              info['is_service_order'] == 1 ? '服务进度' : '查看工单',
              normal: true,
              onTap: () {
                if (info['is_service_order'] == 1) {
                  // toast("小程序的也有问题");
                  Get.toNamed(RouteConfig.gongdans, arguments: {
                    'tmlId': info['order_num_id'],
                  });
                } else {
                  Get.toNamed(RouteConfig.gongdan, arguments: {
                    'tmlId': info['order_num_id'],
                  });
                }
              },
            ),
            SizedBox(width: 12.w),
          ]), //

        Visibility(
          visible: rules('a3', info),
          child: Row(children: [
            EsOutLineButton(
              '确认收货',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                print('确认收货');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        ), //确认收货
        Visibility(
          visible: rules('a6', info),
          child: Row(children: [
            RichText(
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              text: TextSpan(
                  text: '自提码：',
                  style: TextStyle(
                      fontSize: EsSizes.XS,
                      color: EsColors.TitleSecondary,
                      fontWeight: EsFontWeights.Normal),
                  children: <TextSpan>[
                    TextSpan(
                        text: info['verification_code'].toString(),
                        style: TextStyle(
                            fontSize: EsSizes.LG,
                            color: EsColors.TitleSecondary,
                            fontWeight: EsFontWeights.Medium)),
                  ]),
            ),
            SizedBox(width: 12.w),
          ]),
        ), //自提码

        /// 加入购物车
        Visibility(
          visible: rules('a24', info) &&
              info['item_details'].length != 1 &&
              info['item_details'][0]['fresh_type'] != 8,
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                // info['item_details'].forEach((element) {
                //   logic.buyAgain(element, info['ec_shop_num_id']);
                // });
                // logic.buyAgain(info);
                logic.buyAgain2(info['order_num_id'].toString());
              },
              text: '加入购物车',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 超级团补差价
        Visibility(
          visible: rules('a23', info),
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                final logic = Get.put(OrderLogic());
                final state = Get.find<OrderLogic>().state;
                logic.state.total['all_payment'] = info['need_pay_amount'];

                // SpUtil.putString('tml_num_id', info['tml_num_id']);
                SpUtil.putString('order_num_id', info['order_num_id']);
                SpUtil.putDouble('need_pay_amount', info['need_pay_amount']);
                if (info['card_type'] == 1 ||
                    state.GiftcardList.length == 0 ||
                    info['ec_shop_num_id'] != SpUtil.getInt('storeShopNum')) {
                  //直接调起微信支付
                  // logic.goToMoney(info['tml_num_id']);
                  logic.goToMoney(info['order_num_id']);
                  return;
                }
                //如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
                if (info['card_type'] == 0) {
                  // 福利卡可多选
                  // 如果
                  payBottomSheet.showPay(
                      context, logic.state, logic.goToMoney, logic.setGift,
                      // tmlnumid: info['tml_num_id']);
                      tmlnumid: info['order_num_id']);
                }
              },
              text: '补差价',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 超级团退团 需要补差价
        Visibility(
            visible: rules('a22', info),
            child: Padding(
              padding: const EdgeInsets.only(right: 6),
              child: soSignPayBtn(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 10,
                            ),
                            Align(
                              child: Text("确定要取消吗?"),
                              alignment: Alignment(0, 0),
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          CupertinoDialogAction(
                            child: Text("否"),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoDialogAction(
                            child: Text("是"),
                            onPressed: () {
                              // print('___________________');
                              // print(info['so_sign']);
                              // print(info['operate_status_num_id']);
                              // print(info['need_pay_amount']);
                              // print(info['need_pay_amount']);
                              // print(info['cancel_deposit']);
                              // print('___________________');
                              // return;
                              logic.refund(info: info);
                            },
                          ),
                        ],
                      );
                    },
                  );
                },
                text: '退团',
                fontSize: 12,
                showTimerValue: false,
              ),
            )),

        /// 超级团退团 不需要补差价
        Visibility(
            visible: rules('a25', info),
            child: Padding(
              padding: const EdgeInsets.only(right: 6),
              child: soSignPayBtn(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 10,
                            ),
                            Align(
                              child: Text("确定要取消吗?"),
                              alignment: Alignment(0, 0),
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          CupertinoDialogAction(
                            child: Text("否"),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoDialogAction(
                            child: Text("是"),
                            onPressed: () {
                              // print('/////////////////////');
                              // print(info['so_sign']);
                              // print(info['operate_status_num_id']);
                              // print(info['need_pay_amount']);
                              // print(info['need_pay_amount']);
                              // print(info['cancel_deposit']);
                              // print('/////////////////////');
                              // return;
                              logic.refund(info: info);
                            },
                          ),
                        ],
                      );
                    },
                  );
                },
                text: '退团',
                fontSize: 12,
                showTimerValue: false,
              ),
            )),

        /// 定金预售付预售尾款
        Visibility(
          visible: rules('a21', info),
          child: Padding(
            padding: const EdgeInsets.only(right: 6),
            child: soSignPayBtn(
              onTap: () {
                /// 付尾款日期 balance_start_dtme
                Get.toNamed(RouteConfig.endSaleOrder, arguments: {
                  'shop_id': info['ec_shop_num_id'],
                  'shopnum': 1,
                  'tml_num_id': info['order_num_id'],
                  'isFontSale': false,
                  'card_type': info['card_type']
                });
              },
              text: '付预售尾款',
              fontSize: 12,
              showTimerValue: false,
            ),
          ),
        ),

        /// 定金预售退预售定金
        Visibility(
            visible: rules('a20', info),
            child: Padding(
              padding: const EdgeInsets.only(right: 6),
              child: soSignPayBtn(
                onTap: () {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return CupertinoAlertDialog(
                        title: Text("提示"),
                        content: Column(
                          children: <Widget>[
                            SizedBox(
                              height: 10,
                            ),
                            Align(
                              child: Text("确定要取消吗?"),
                              alignment: Alignment(0, 0),
                            ),
                          ],
                        ),
                        actions: <Widget>[
                          CupertinoDialogAction(
                            child: Text("否"),
                            onPressed: () {
                              Navigator.pop(context);
                            },
                          ),
                          CupertinoDialogAction(
                            child: Text("是"),
                            onPressed: () {
                              logic.refund(info: info);
                            },
                          ),
                        ],
                      );
                    },
                  );
                },
                text: '退预售定金',
                fontSize: 12,
                showTimerValue: false,
              ),
            )),

        // EsOutLineButton(
        //   '再来一单',
        //   onTap: () {
        //     print('再来一单');
        //   },
        // ),
        // SizedBox(width: 12.w),
        if (info["comment_type"] == 0 && info["so_sign_name"] == "正常")
          Row(children: [
            EsOutLineButton(
              '评价晒单',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                //评价晒单 跳转
                // print('  评价参数   widget.data = ${widget.data} ');
                var params = {
                  'use_platform': 2,
                  'access_token': SpUtil.getString('token'),
                  'usr_num_id': SpUtil.getInt('empeNumId'),
                };

                Api.viewEvaluationPermission(params).listen((event) {
                  if (event['code'] == 0) {
                    String blackType = event['black_type'].toString();
                    if (!blackType.contains('2')) {
                      // print(">>>>>$info");
                      // return;
                      Get.toNamed(
                        RouteConfig.pingJiaShaiDan,
                        arguments: info,
                      );
                      return;
                    }
                  } else {
                    toast('评价权限暂时关闭，请联系客服');
                  }
                }, onError: (error) {});
                print('晒单评价');
              },
            ),
            SizedBox(width: 12.w),
          ]),
        if (info["comment_type"] == 2)
          Row(children: [
            EsOutLineButton(
              '查看评价',
              bgColor: EsColors.Primary,
              textColor: EsColors.White,
              onTap: () {
                //评价晒单 跳转
                // print('  评价参数   widget.data = ${widget.data} ');
                var params = {
                  'use_platform': 2,
                  'access_token': SpUtil.getString('token'),
                  'usr_num_id': SpUtil.getInt('empeNumId'),
                };

                Api.viewEvaluationPermission(params).listen((event) {
                  if (event['code'] == 0) {
                    print(info);
                    // return;
                    // String blackType = event['black_type'].toString();
                    Get.toNamed(
                      RouteConfig.viewComments,
                      arguments: info,
                    );
                  } else {
                    toast('评价权限暂时关闭，请联系客服');
                  }
                }, onError: (error) {});
                print('晒单评价');
              },
            ),
            SizedBox(width: 12.w),
          ]),

        if (info["consumer_invoice_sign"] == 1)
          EsOutLineButton(
            '查看发票',
            normal: true,
            onTap: () {
              // // return;
              Get.toNamed(RouteConfig.drawBillPageDetail,
                  arguments: {'tml_num_id': info['order_num_id']});
            },
          ),
        // info["consumer_invoice_sign"] == 0 &&
        if (info["consumer_invoice_sign"] == 0 &&
            info["order_status"] != 9 &&
            (info["status_num_id"] == 3 || info["status_num_id"] == 6))
          EsOutLineButton(
            '申请发票',
            normal: true,
            onTap: () {
              print('申请发票${info['order_num_id']}');
              // return;
              Get.toNamed(RouteConfig.drawBillPage,
                  arguments: {'tml_num_id': info['order_num_id']});
            },
          ),
        SizedBox(width: 12.w),
        if (info["cancel_button"] == 1)
          EsOutLineButton(
            '取消退款/退货',
            normal: true,
            onTap: () {
              showDialog(
                context: context,
                builder: (BuildContext context) {
                  return CupertinoAlertDialog(
                    title: Text("提示"),
                    content: Column(
                      children: <Widget>[
                        SizedBox(
                          height: 10,
                        ),
                        Align(
                          child: Text("确认取消退款？"),
                          alignment: Alignment(0, 0),
                        ),
                      ],
                    ),
                    actions: <Widget>[
                      CupertinoDialogAction(
                        child: Text("取消"),
                        onPressed: () {
                          Navigator.pop(context);
                          print("取消");
                        },
                      ),
                      CupertinoDialogAction(
                        child: Text("确定"),
                        onPressed: () {
                          print(info);
                          var params = {
                            'access_token': SpUtil.getString('token'),
                            'tml_operation_type': 3,
                            'tml_num_id': info['order_num_id'],
                            'usr_num_id': SpUtil.getInt('empeNumId'),
                          };
                          Get.back();
                          Api.cxtk(params).listen((event) {
                            if (event['code'] == 0) {
                              toast('撤销成功');
                            } else {
                              toast(event['message']);
                            }
                          });
                        },
                      ),
                    ],
                  );
                },
              );
            },
          ),
        SizedBox(width: 12.w),
      ],
    );
  }

  @override
  void dispose() async {
    super.dispose();
    _refreshController.dispose();

    print('dispose Finish');
  }

  @override
  bool get wantKeepAlive => true;
}

Widget soSignPayBtn({
  Function onTap,
  String text = '去付款',
  double fontSize,
  bool showTimerValue = true,
  String timerValue = '',
}) {
  return GestureDetector(
    onTap: onTap,
    child: Container(
      decoration: BoxDecoration(
          color: EsColors.Primary, borderRadius: BorderRadius.circular(20.0)),
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
      child: Text(
        showTimerValue ? text + timerValue : text,
        style: TextStyle(
            fontSize: fontSize ?? EsSizes.SM,
            color: EsColors.White,
            fontWeight: EsFontWeights.Normal),
      ),
    ),
  );
}

//倒计时按钮
class TimeButton extends StatefulWidget {
  var info;

  TimeButton(this.info, BuildContext context, {Key key}) : super(key: key);

  @override
  _TimeButtonState createState() => _TimeButtonState();
}

class _TimeButtonState extends State<TimeButton> {
  String timerValue = '';
  var timer;

  @override
  void initState() {
    if (widget.info['residue_time'] == null ||
        widget.info['residue_time'] < 0) {
      timerValue = '';
    } else {
      int seconds = widget.info['residue_time'] ~/ (1000);
      // int seconds =111111 ~/ (1000);
      timer = Timer.periodic(Duration(seconds: 1), (timer) {
        setState(() {
          var d = Duration(seconds: seconds);
          List<String> parts = d.toString().split(':');
          timerValue = '${parts[0]}:${parts[1]}:${parts[2].split('.')[0]}';
        });

        if (seconds == 0) {
          timer.cancel();
          return;
        }
        seconds = --seconds;
      });
    }

    // Start
    print('订单item');
    print(widget.info);
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() async {
    print('这是销毁');
    timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        final logic = Get.put(OrderLogic());
        final state = Get.find<OrderLogic>().state;
        logic.state.total['all_payment'] = widget.info['need_pay_amount'];

        // SpUtil.putString('tml_num_id', widget.info['tml_num_id']);
        SpUtil.putString('order_num_id', widget.info['order_num_id']);
        SpUtil.putDouble('need_pay_amount', widget.info['need_pay_amount']);
        if (widget.info['card_type'] == 1 ||
            state.GiftcardList.length == 0 ||
            widget.info['ec_shop_num_id'] != SpUtil.getInt('storeShopNum')) {
          //直接调起微信支付
          // logic.goToMoney(widget.info['tml_num_id']);
          logic.goToMoney(widget.info['order_num_id']);
          return;
        }
        //如果是 0， 需要查询福利卡，减去福利卡金额  （total_amount）- 福利卡金额
        if (widget.info['card_type'] == 0) {
          // 福利卡可多选
          // 如果
          payBottomSheet.showPay(
              context, logic.state, logic.goToMoney, logic.setGift,
              // tmlnumid: widget.info['tml_num_id']);
              tmlnumid: widget.info['order_num_id']);
        }
      },
      child: widget.info['so_sign'] == 16
          ? Container()
          : Container(
              decoration: BoxDecoration(
                  color: EsColors.Primary,
                  borderRadius: BorderRadius.circular(20.0)),
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              child: Text(
                '去付款' + timerValue,
                style: TextStyle(
                    fontSize: 11,
                    color: EsColors.White,
                    fontWeight: EsFontWeights.Normal),
              ),
            ),
    );
  }
}
